import 'package:dk_flutter_base/dk_core.dart';
import 'package:dk_flutter_base/dk_ui.dart';
import 'package:dk_flutter_module_sale/common/config/page_base_common.dart';
import 'package:dk_flutter_module_sale/common/user_track/user_track.dart';
import 'package:dk_flutter_module_sale/config/route/common_widget_route.dart';
import 'package:dk_flutter_module_sale/sale/api/sale_in_map_tool_api.dart';
import 'package:dk_flutter_module_sale/sale/sale_in/map_tool/bean/bean_configure.dart';
import 'package:flutter_dk_form/flutter_dk_form.dart';
import 'package:flutter/cupertino.dart';

@ARoute(url: CommonWidgetRoute.COMMON_HOUSE_SOURCE_FOLLOWING_DETAIN)
class PageHouseSourceFollowingDetail extends CommonPageWithTrack {
  final BoostRouteOption option;
  final String id;
  PageHouseSourceFollowingDetail(this.option)
      : this.id = (option?.params["id"] is num)
            ? (option?.params["id"] as num).toInt().toString()
            : option?.params["id"].toString(),
        super();

  @override
  void trackStatistics() {
    UserTrack.trackViewScreen("收房-目标房源-详情", null);
  }

  @override
  void onInitState(CommonPageBloc pageBloc, {Map<String, Bloc> extraBlocMap}) {
    // 获取配置
    pageBloc.pageHttpGet(
      path:
          SaleInMapToolApi.houseSourceDetailConfig, //SaleInApi.mapCloseReason,
      queryMap: {'configurationType': 'CLOSE_TASK_REASON'},
      widgetBuilderByData: (dynamic data) {
        BeanConfigure beanConfigure =
            BeanConfigure.fromJson(data) ?? BeanConfigure();
        List<DkDropDownItem> list = List<DkDropDownItem>();
        for (ListItemBean bean in beanConfigure.list) {
          list.add(DkDropDownItem(bean.value, bean.label));
        }
        return FollowUpDetailPage(pageBloc, list, id);
      },
      handleErrorCode: (responseData) {
        showToast(responseData.msg);
      },
      showFailMsg: true,
    );
    UserTrack.trackViewScreen('', null);
  }
}

class FollowUpDetailPage extends StatefulWidget {
  final CommonPageBloc pageBloc;
  final List<DkDropDownItem> list;
  final String id;

  FollowUpDetailPage(this.pageBloc, this.list, this.id);

  @override
  _FollowUpDetailState createState() => _FollowUpDetailState();
}

class _FollowUpDetailState extends State<FollowUpDetailPage> {
  String houseId = '';
  bool close = true;
  int reason = 0;
  String address = '';

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      bottom: true,
      child: Scaffold(
        appBar: DkAppBar(DKAppBarParams.withBackNoMenu(widget.pageBloc.context,
            titleContent: "房源跟进详情")),
        backgroundColor: Colors.white,
        resizeToAvoidBottomPadding: true,
        body: Column(
          children: <Widget>[
            Expanded(
              child: Container(
                color: Color(0xFFF7F8FA),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    SwitchChoiceItemWidget(
                      rightText: '是',
                      leftText: '否',
                      title: '关闭任务',
                      open: close,
                      isLine: true,
                      tapCallback: (value) {
                        setState(() {
                          close = value;
                        });
                      },
                    ),
                    Offstage(
                      offstage: close == true,
                      child: SingleInputWidget(
                        title: '房源ID',
                        hintText: '请输入渠道推送的房源ID',
                        onChanged: (value) {
                          houseId = value != null ? value : '';
                        },
                      ),
                    ),
                    Offstage(
                      offstage: close == false,
                      child: Column(
                        children: <Widget>[
                          DropDownWidget(
                            title: '关闭原因',
                            placeHolder: '请选择关闭任务原因',
                            items: widget.list,
                            onChanged: (value) {
                              setState(() {
                                reason = value.value;
                              });
                            },
                            hasLine: true,
                          ),
                          Offstage(
                            offstage: reason != 3,
                            child: SingleInputWidget(
                              title: '记录房源地址',
                              hintText: '请输入房源地址',
                              onChanged: (value) {
                                address = value != null ? value : '';
                              },
                              hasLine: false,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
            BottomButtonWidget(
              onCommit: _submit,
              onCancel: _close,
            ),
          ],
        ),
      ),
    );
  }

  void _close() {
    RouteUtil.closeCurrentPage({});
  }

  void _submit() {
    String url = SaleInMapToolApi.houseSourceDetailTask;
    debugPrint('houseId = $houseId close=$close reason=$reason');
    if (close == true && reason == 0) {
      showToast("请选择关闭原因");
      return;
    }
    if (close == true && reason == 3 && address.isEmpty) {
      showToast("请填写房源地址");
      return;
    }
    if (close == false && houseId.isEmpty) {
      showShortToast('请填写房源ID');
      return;
    }
    Map<String, dynamic> data = Map<String, dynamic>();
    if (close == true) {
      data['isCloseTask'] = close;
      data['taskCloseReason'] = reason;
      if (reason == 3) {
        data['houseAddress'] = address;
      }
    } else {
      data['isCloseTask'] = close;
      data['houseId'] = houseId;
    }

    widget.pageBloc.dataHttpPost(
      path: '$url/${widget.id}/follow-up',
      data: data,
      handleResult: (data) {
        RouteUtil.closeCurrentPage({});
      },
      handleErrorCode: (responseData) {
        showToast(responseData.msg);
      },
      showFailMsg: true,
    );
  }
}
